using AutoMapper;
using Microsoft.EntityFrameworkCore;
using PowerManage.EntityFrameworkCore;
using PowerManage.Entity.Dtos.Roles;
using PowerManage.Entity.Dtos.Users;

namespace PowerManage.Service.Impl;

public class RoleService : BaseService, IRoleService
{
    private readonly ApplicationDbContext _dbContext;
    private readonly IMapper _mapper;

    public RoleService(ApplicationDbContext dbContext, IMapper mapper)
    {
        _dbContext = dbContext;
        Console.WriteLine("角色：" + _dbContext.ContextId);
        _mapper = mapper;
    }

    /// <summary>
    /// 角色搜索
    /// </summary>
    /// <param name="rolePageReqDto"></param>
    /// <returns></returns>
    public async Task<RolePageRspDto> Query(RolePageReqDto rolePageReqDto)
    {
        //创建返回对象
        var result = new RolePageRspDto();
        // 获取所有角色记录的查询对象 延迟执行(在需要时才执行)
        var query = _dbContext.Roles.AsQueryable();
        if (!string.IsNullOrEmpty(rolePageReqDto.Name))
        {
            query = query.Where(x => x.Name != null && x.Name.Equals(rolePageReqDto.Name));
        }

        // 页数至少为1
        rolePageReqDto.CurrentPage = rolePageReqDto.CurrentPage > 0 ? rolePageReqDto.CurrentPage : 1;
        //获取总数和用户列表
        var count = await query.CountAsync();
        var list = await query.OrderByDescending(x => x.CreationTime)
            .Skip((rolePageReqDto.CurrentPage - 1) * rolePageReqDto.PageSize)
            .Take(rolePageReqDto.PageSize)
            .ToListAsync();
        //填充返回对象
        result.CurrentPage = rolePageReqDto.CurrentPage;
        result.PageSize = rolePageReqDto.PageSize;
        result.TotalCount = count;
        //转换实体
        var roleDtos = new List<RoleDto>();
        foreach (var role in list)
        {
            var roleDto = _mapper.Map<RoleDto>(role);
            //填充创建者 从这些用户中找到第一个符合条件的用户
            var user = _dbContext.Users.FirstOrDefault(x => x.Id == roleDto.Id);
            roleDto.Creator = _mapper.Map<UserDto>(user);
            roleDtos.Add(roleDto);
        }

        result.Roles = roleDtos;
        return result;
    }

    /// <summary>
    /// 获取所有角色列表
    /// </summary>
    /// <returns></returns>
    public async Task<List<RoleDto>> GetAll()
    {
        //获取所有角色列表 
        var list = await _dbContext.Roles.ToListAsync();
        var roleDtos = new List<RoleDto>();
        //转换实体
        foreach (var role in list)
        {
            var roleDto = _mapper.Map<RoleDto>(role);

            //创建者
            var user = _dbContext.Users.FirstOrDefault(x => x.Id == roleDto.Id);
            roleDto.Creator = _mapper.Map<UserDto>(user);
            roleDtos.Add(roleDto);
        }

        return roleDtos;
    }
}